﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Linq;
using System.Xml.Linq;

namespace TweetFeedWp7
{
    public delegate void FeedReadyEventHandler(object sender, FeedReadyArg e);

    public class Feed
    {

        public event FeedReadyEventHandler FeedReady;

        // Invoke the Changed event; called whenever list changes
        protected virtual void OnFeedReady(FeedReadyArg e)
        {
            if (FeedReady != null)
                FeedReady(this, e);
        }


        private string defaultMessage;
        private readonly Queue<string> feedsToFetch;
        public Feed(string defaultMessage)
        {
            this.defaultMessage = defaultMessage;
            this.feedsToFetch = new Queue<string>();
            
        }

        
        public void GetFeedsForList(List<string> screenNames)
        {
            if (screenNames == null || screenNames.Count == 0)
            {
                System.Diagnostics.Debug.WriteLine("nothing to fetch");
                return;
            }


            int count = feedsToFetch.Count; //TODO: not thread safe but not dangerous
            screenNames.ForEach(n => feedsToFetch.Enqueue(n));

            if (count == 0)
            {
                NextFeed();
            }
        }
  
        public void NextFeed()
        {
            string firstName = feedsToFetch.Dequeue();
            GetFeedsAsync(firstName);
        }

        
        public void GetFeedsAsync(string screenName)
        {
            System.Diagnostics.Debug.WriteLine("Asking for " + screenName);
            
            if (string.IsNullOrWhiteSpace(screenName))
            {
                FinishedBatched = (feedsToFetch.Count == 0);
                OnFeedReady(new FeedReadyArg { Messages = new List<string>{defaultMessage}, TwitterName = screenName });
                return;
            }
            WebClient http = new WebClient();
            http.DownloadStringCompleted += HttpDownloadStringCompleted;
            try
            {
                http.DownloadStringAsync(new Uri("http://api.twitter.com/1/statuses/user_timeline.xml?screen_name=" + screenName), screenName);
            }
            catch (Exception e)
            {
                System.Diagnostics.Debug.WriteLine(e.Message);
                FinishedBatched = (feedsToFetch.Count == 0);
                OnFeedReady(new FeedReadyArg { Messages = new List<string> { "GetFeedAync " + e.Message + " " + defaultMessage }, TwitterName = screenName });
            }
        }

        void HttpDownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
        {
            System.Diagnostics.Debug.WriteLine("recieved tweets result");

            if (e.Error == null && !e.Cancelled)
            {
                string tweetsAsXml = e.Result;

                XDocument loaded = XDocument.Parse(tweetsAsXml);
                var tweets = (from s in loaded.Descendants("status")
                              select (string)s.Element("text")).ToList();
                
                FinishedBatched = (feedsToFetch.Count == 0);
                OnFeedReady(new FeedReadyArg { Messages = tweets, TwitterName = e.UserState.ToString() });

            }
            else
            {
                FinishedBatched = (feedsToFetch.Count == 0);
                OnFeedReady(new FeedReadyArg { Messages = new List<string> { "Feed Problem " + defaultMessage + defaultMessage + defaultMessage + defaultMessage }, TwitterName = e.UserState.ToString() });
            }
                        
            
        }



        public bool FinishedBatched 
        { get; 
            set; }
    }
}
